package com.flywen.utils;

import com.flywen.exception.AppException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpRequestUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestUtil.class);
    private static int maxConnPerRoute = 512;
    private static int maxTotalConn = 512;
    private static int DEFAULT_CONN_TIME_OUT = 3000;
    private static int DEFAULT_WAIT_TIME_OUT = 6000;
    private static final String DEFAULT_CONTENT_ENCODING = "UTF-8";
    private static ThreadSafeClientConnManager connectionManager = null;

    static {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
        connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
        connectionManager.setMaxTotal(maxTotalConn);
        connectionManager.setDefaultMaxPerRoute(maxConnPerRoute);
    }

    public HttpRequestUtil() {
    }

    public static String executePost(String url, List<? extends NameValuePair> params, int connTimeOut, int soTimeOut, String charset) {
        HttpPost httpPost = new HttpPost(url);

        UrlEncodedFormEntity reqEntity;
        try {
            reqEntity = new UrlEncodedFormEntity(params, charset);
        } catch (IOException var8) {
            LOGGER.error("executePost error,url:" + url, var8);
            throw new AppException("9999", "executePost fail");
        }

        httpPost.setEntity(reqEntity);
        String result = execute(httpPost, url, connTimeOut, soTimeOut, charset);
        LOGGER.debug("[HttpClientTemplate:executePost()]: [url={}]: [response={}] send successful!", url, result);
        return result;
    }

    public static String executePost(String url, Map<String, String> params) {
        return executePost(url, params, "UTF-8");
    }

    public static String executePost(String url, Map<String, String> params, String charset) {
        List<BasicNameValuePair> basicNameValuePairs = new ArrayList <>();
        if (params != null) {
            Iterator var5 = params.keySet().iterator();

            while(var5.hasNext()) {
                String key = (String)var5.next();
                basicNameValuePairs.add(new BasicNameValuePair(key, (String)params.get(key)));
            }
        }

        return executePost(url, (List)basicNameValuePairs, 0, 0, charset);
    }

    public static String executePost(String url, Map<String, String> params, int timeOut, int soTimeOut, String charset) {
        List<BasicNameValuePair> basicNameValuePairs = new ArrayList();
        if (params != null) {
            Iterator var7 = params.keySet().iterator();

            while(var7.hasNext()) {
                String key = (String)var7.next();
                basicNameValuePairs.add(new BasicNameValuePair(key, (String)params.get(key)));
            }
        }

        return executePost(url, (List)basicNameValuePairs, timeOut, soTimeOut, charset);
    }

    public static String executePost(String url, Map<String, String> params, int timeOut, int soTimeOut) {
        return executePost(url, params, timeOut, soTimeOut, "UTF-8");
    }

    public static String executePost(String url, String params, int timeOut, int soTimeOut) {
        HttpPost httpPost = new HttpPost(url);

        StringEntity reqEntity;
        try {
            reqEntity = new StringEntity(params, "UTF-8");
        } catch (UnsupportedEncodingException var7) {
            throw new AppException("9999", "executePost fail,url" + url);
        }

        httpPost.setEntity(reqEntity);
        String result = execute(httpPost, url, timeOut, soTimeOut, "UTF-8");
        LOGGER.debug("[HttpClientTemplate:executePost()]: [url=" + url + "]: [params=" + params + "]: [response=" + result + "] send successful!");
        return result;
    }

    public static String executePost(String url, String params) {
        return executePost(url, (String)params, 0, 0);
    }

    private static String execute(HttpRequestBase httpReq, String url, int timeOut, int soTimeOut, String charset) {
        HttpClient httpclient = getHttpClient(url, timeOut, soTimeOut);
        StringBuilder sb = new StringBuilder();
        HttpResponse response = null;
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;

        try {
            response = httpclient.execute(httpReq);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                LOGGER.debug("Response content length: " + entity.getContentLength());
                inputStreamReader = new InputStreamReader(entity.getContent(), charset);
                bufferedReader = new BufferedReader(inputStreamReader);
                String line = null;

                while((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }

                return sb.toString();
            }

            LOGGER.info("Response entity is null");
        } catch (Exception var24) {
            LOGGER.debug("execute invoke occour com.wen.exception");
            LOGGER.error("execute invoke occour com.wen.exception", var24);
            throw new AppException("9999", "execute fail" + url);
        } finally {
            if (httpReq != null) {
                httpReq.abort();
            }

            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException var23) {
                    LOGGER.debug("inputStreamReader close fail");
                }
            }

            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException var22) {
                    LOGGER.debug("inputStreamReader close fail");
                }
            }

        }

        return null;
    }

    public static String sendXmlRequest(String url, String xml, int timeOut, int soTimeOut) {
        LOGGER.debug("enter sendXmlRequest,xml:{}", xml);
        StringBuilder result = new StringBuilder();
        HttpClient httpclient = getHttpClient(url, timeOut, soTimeOut);
        HttpPost httppost = null;
        HttpResponse response = null;
        InputStreamReader reader = null;

        try {
            StringEntity myEntity = new StringEntity(xml, "UTF-8");
            httppost = new HttpPost(url);
            httppost.addHeader("Content-Type", "text/xml;charset=utf-8");
            httppost.setEntity(myEntity);
            response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                reader = new InputStreamReader(resEntity.getContent(), "UTF-8");
                char[] buff = new char[1024];
                boolean var12 = false;

                int length;
                while((length = reader.read(buff)) != -1) {
                    result.append(buff, 0, length);
                }
            }
        } catch (Exception var20) {
            LOGGER.debug("sendXmlRequest invoke occur com.wen.exception");
            LOGGER.error("sendXmlRequest invoke occur com.wen.exception ", var20);
            throw new AppException("9999", "sendXmlRequest fail");
        } finally {
            if (httppost != null) {
                httppost.abort();
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException var19) {
                    LOGGER.debug("reader close fail");
                }
            }

        }

        String strResult = result.toString();
        LOGGER.debug("exit sendXmlRequest,response:{}", strResult);
        return strResult;
    }

    public static String sendXmlRequest(String url, String xml) {
        return sendXmlRequest(url, xml, 0, 0);
    }

    public static HttpClient getHttpClient(String url, int timeOut, int soTimeout) {
        timeOut = timeOut == 0 ? DEFAULT_CONN_TIME_OUT : timeOut;
        soTimeout = soTimeout == 0 ? DEFAULT_WAIT_TIME_OUT : soTimeout;
        LOGGER.debug("httpclient not found,new one");
        HttpClient httpclient = new DefaultHttpClient(connectionManager);
        HttpParams params = httpclient.getParams();
        params.setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
        params.setParameter("http.connection.timeout", timeOut);
        params.setParameter("http.socket.timeout", soTimeout);
        return httpclient;
    }

    public static void release() {
        if (connectionManager != null) {
            connectionManager.shutdown();
        }

    }
}
